export default {
  data() {
    return {
      isFormGetEnd: false,
      isSaveLoding: false,
      loading: false,
      formFormatData: {},
      formFormatEach: [],
      afterOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7
        },
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            end.setTime(start.getTime() + 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            end.setTime(start.getTime() + 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            end.setTime(start.getTime() + 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }]
      }
    }
  },
  filters: {
    address(scope) {
      return `${scope.province[0]['value']}-${scope.city[0]['value']}-${scope.area[0]['value']}`
    }
  },
  created() {
    this.$nextTick(() => {
      const { noCreateEdit, isReset } = this['formFormatData']['model'] || {}
      if (isReset) {
        this.copyFormEmpty()
      }

      if (!noCreateEdit) {
        this.formFormatEditEvt()
      }
    })
  },
  computed: {
    isFormEdit() {
      const { editForm: { params = {}, redirect = 'id' } } = this.formFormatData.api
      const key = this.$route.query[redirect]
      return params.always || (key && (key !== ''))
    },
    hasFormEditRouteId() {
      const { editForm } = this.formFormatData.api
      if (editForm) {
        const { redirect = 'id' } = editForm
        return Object.keys(this.$route.query).includes(redirect)
      }
    },
    isDialogEdit() {
      const { editForm: { params = {}, redirect = 'id' } } = this.formFormatData.api
      console.log(params[redirect])
      return !!params[redirect]
    },
    isFormFormatSave() {
      console.log("+++++++++++++---------------",this.isSaveLoding)
      return this.isSaveLoding
    },
    isFormFormatGetEnd() {
      return this.isFormGetEnd
    }
    // formFormatList() {
    //   return Object.keys(this.formFormatData)
    // },
    // validateFormList() {
    //   const result = []
    //   if (this.formFormatList.length > 0) {
    // this.formFormatList.map((item) => {
    //   if (this.formFormatData[item]['isCheck']) {
    // result.push(this.formFormatData[item]['key'])
    //   }
    // })
    //   }
    //   return result
    // },
    // hasValidate() {
    //   return this.validateFormList.length > 0
    // }
  },
  methods: {
    notZero(params) {
      console.log(params)
    },
    clearNativeReg(params) {
      console.log(params)
    },
    newGiftChange(params) {
      console.log(params)
    },
    copyFormEmpty(copyForm = false) {
      const [formCopyData = {}] = require('@/filters/index').assignCopy(copyForm || this['formFormatData']['formData'])
      this.formCopyEmpty = formCopyData
    },
    formFormatDialogEditEvt({ id = null, params = {}, toggle = '', noEdit = false }) {
      this[`${toggle}`] = true
      if (id) {
        Object.assign(this['formFormatData']['api']['editForm']['params'], params)
        console.log('1', Object.assign(this['formFormatData']['api']['editForm']['params'], params))

        this['formFormatData']['api']['editForm']['params'][`${this.formFormatData.api['editForm']['redirect'] || 'id'}`] = id
        this['formFormatData']['formData'][`${this.formFormatData.api['editForm']['redirect'] || 'id'}`] = id
      }
      if (!noEdit) {
        this.formFormatEditEvt(true)
      }
    },
    formFormatFiltersChange(filslist, bindKey = {}) {
      const { key, model, validateField = [] } = bindKey
      let keyType = 'unknown'
      if (typeof key === 'string') {
        keyType = 'String'
      } else if (Array.isArray(key)) {
        keyType = 'Array'
      }
      this.formFormatFiltersParams(keyType, key, model, filslist, validateField)
    },
    formFormatFiltersEach(params, formData) {
      this.formFormatEach = []
      this.formFormatFiltersLoop(params, formData)
    },
    formFormatFiltersLoop(params, formData) {
      params.forEach(key => {
        const tmp = formData[`${key}`]
        if (formData[`${key}`]) {
          params.splice(0, 1)
          this.formFormatFiltersEach(params, formData[`${key}`])
        }
        this.formFormatEach.push(tmp)
      })
    },
    formFormatFiltersParams(keyType, key, model, filslist, validateField) {
      console.log('----------------------------------------------------------------------')
      const formatData = this.formFormatData.formData
      if (model === 'img' || model === 'video') {
        const isReset = key.includes('|')
        let scopeData = {}
        if (isReset) {
          const keyList = key.split('|')
          key = keyList[keyList.length - 1]
          this.formFormatFiltersEach(keyList, formatData)
          console.log(this.formFormatEach)
          scopeData = this.formFormatEach[1]
          console.log(scopeData)
        } else {
          scopeData = formatData
        }

        if (keyType === 'String') {
          if (Array.isArray(filslist.currentRow) && Array.isArray(filslist.displayData) && filslist.key === 'ChooseFiles') {
            const { displayData } = filslist
            // console.log(displayData, isLimitMax, 'isLimitMax')
            scopeData[`${key}`] = displayData
            // console.log(!isLimitMax, scopeData[`${key}`], 'console.log(currentRow,displayData)')
          } else {
            if (Array.isArray(filslist)) {
              scopeData[`${key}`] = []
              filslist.map((imgItem) => {
                scopeData[`${key}`]['push'](imgItem)
              })
            } else {
              scopeData[`${key}`] = filslist[0]
            }
          }
        }
      } else if (model === 'map') {
        const point = Object.keys(filslist)
        key.map((item, index) => {
          if (!!item.name && item.type === 'String' && point.length > 0) {
            formatData[`${item.name}`] = filslist[`${item.name}`]
          }
        })
      } else if (model === 'address') {
        if (keyType === 'Array') {
          key.map((item, index) => {
            if (!!item.name && item.type === 'String') {
              formatData[`${item.name}`] = item.isId ? filslist[0].id : filslist[0]
              console.log(formatData[`${item.name}`])
              filslist.shift()
            }
          })
        }
      } else if (model === 'choose') {
        if (keyType === 'String') {
          const { displayData } = filslist
          if (Array.isArray(displayData)) {
            formatData[`${key}`] = displayData
          }
        }
      }

      if (Array(validateField) && validateField.length > 0) {
        this.validateField(validateField)
      }
    },
    formFormatEditEvt(isEdit) {
      if (isEdit || this.formFormatData.api['editForm'] && this.formFormatData.api['editForm']['api'] && ((this.$route.query && Object.keys(this.$route.query).includes(this.formFormatData.api['editForm']['redirect'] || 'id')) || (this.formFormatData.api['editForm']['params'] && this.formFormatData.api['editForm']['params']['always']))) {
        // console.log(this.$route.query)
        this.formFormatData.api['editForm']['api'](Object.assign(this.formFormatData.api['editForm']['params'] || {}, this.$route.query || {})).then((response) => {
          const { data: { data: formatData = {} } = {} } = response
          console.log(response, 'response')
          if (!Object.is(formatData, null)) {
            this.$nextTick(() => {
              const filtersFormat = {}
              const paramsKey = Object.keys(formatData)
              const hasParamsKey = Object.keys(this['formFormatData']['formData'])
              const noFilter = this.formFormatData.api['editForm']['noFilter']
              // const resetFilter = this.formFormatData.api['editForm']['resetFilter']
              paramsKey.map((item, index) => {
                if (noFilter && noFilter.includes(item)) {
                  filtersFormat[item] = formatData[item]
                } else if (hasParamsKey.includes(item)) {
                  filtersFormat[item] = formatData[item]
                }
              })

              // if (resetFilter && resetFilter.length > 0) {
              //   resetFilter.map(item => {
              // const { key, type, reset } = item
              // if (key.includes('|')) {
              //   const keyList = key.split('|')
              //   const $key = keyList[keyList.length - 1]
              //   this.formFormatFiltersEach(keyList, filtersFormat)
              //   const [scopeData, parentData] = this.formFormatEach
              //   if (type === 'Array' && (!Array.isArray(scopeData) || !scopeData)) {
              // parentData[`${$key}`] = reset
              //   }
              // } else {
              //   filtersFormat[`${key}`] = reset
              // }
              //   })
              // }

              this.formFormatCallBack && this.formFormatCallBack(filtersFormat, 'editBeforeForm', response)
              // console.log(this['formFormatData']['formData'], filtersFormat)
              Object.assign(this['formFormatData']['formData'], Object.assign(filtersFormat, this.$route.query || {}))
              console.log(Object.assign(this['formFormatData']['formData'], Object.assign(filtersFormat, this.$route.query || {})), '===12')
              this.formFormatCallFilters(this.formFormatData.api || {}, filtersFormat)
              this.isFormGetEnd = true
              this.formFormatCallBack && this.formFormatCallBack(this['formFormatData']['formData'], 'editForm', response)
            })
          }
        })
      }
    },
    formFormatCallFilters({ editForm = {} }, formatData) {
      const { filters = {} } = editForm
      console.log(filters, '==================filrter')
      const hasFilters = Object.keys(filters)
      console.log(hasFilters, '======================>hasFilters')
      if (hasFilters.length > 0) {
        hasFilters.map((item, index) => {
          if (item === 'img' || item === 'video') {
            const { bindInit } = filters[item]
            this.formFormatCallFiltersEach(bindInit, formatData, (bindItem, initData) => {
              if (Array.isArray(initData)) {
                initData.map((imgItem) => {
                  this[bindItem].initList.push(imgItem)
                })
              }
            })
          } else if (item === 'map') {
            const { bindInit } = filters[item]
            console.log(bindInit, '====================>map')
            this.formFormatCallFiltersEach(bindInit, formatData, (bindItem, initData, name) => {
              this[bindItem].initList.push({ 'name': name, 'value': initData })
            })
          } else if (item === 'address') {
            const { bindInit } = filters[item]
            console.log(bindInit, '==================bindInit')
            this.formFormatCallFiltersEach(bindInit, formatData, (bindItem, initData, name) => {
              if (Array.isArray(initData)) {
                this[bindItem].initList.push(initData)
              } else if (typeof initData === 'object' && initData['id']) {
                this[bindItem].initList.push(initData)
              }
            })
          } else if (item === 'choose') {
            const { bindInit } = filters[item]
            this.formFormatCallFiltersEach(bindInit, formatData, (bindItem, initData, name) => {
              if (Array.isArray(initData)) {
                this[bindItem].initList = initData
              }
            })
          }
        })
      }
    },
    formFormatCallFiltersEach(bindInit, formatData, callback, isReset = false) {
      if (Array.isArray(bindInit) && bindInit.length > 0) {
        bindInit.map((bindItem, bindIndex) => {
          console.log(bindItem, 'bindItem')
          const { initList, bindKey = {} } = this[bindItem]
          const isLoop = bindKey.key && bindKey.key.includes('|')
          let scopeData = {}
          let scopeKey = null
          if (isLoop) {
            const keyList = bindKey.key.split('|')
            scopeKey = keyList[keyList.length - 1]
            this.formFormatFiltersEach(keyList, formatData)
            scopeData = this.formFormatEach[1]
            // console.log(scopeData, 'xfdf')
          }
          if (Array.isArray(initList)) {
            if (typeof bindKey.key === 'string') {
              if (!isReset) {
                const initData = isLoop ? scopeData[`${scopeKey}`] : formatData[`${bindKey.key}`]
                if (initData) {
                  callback(bindItem, initData)
                }
              } else {
                callback(bindItem)
              }
            } else if (Array.isArray(bindKey.key)) {
              bindKey.key.map((keyItem, keyIndex) => {
                if (!isReset) {
                  const initData = formatData[`${keyItem.name}`]
                  if (initData) {
                    callback(bindItem, initData, keyItem.name)
                  }
                } else {
                  callback(bindItem)
                }
              })
            }
          }
        })
      }
    },
    validateField(validate) {
      if (typeof validate === 'string') {
        if (Array.isArray(this.formFormatData['key'])) {
          this.formFormatData['key'].map((item) => {
            this.$refs[`${item}`] && this.$refs[`${item}`].validateField(validate)
          })
        } else {
          this.$refs[this.formFormatData['key']].validateField(validate)
        }
      }
    },
    resetField(current) {
      if (current) {
        this.$refs[current].resetFields()
      } else {
        if (Array.isArray(this.formFormatData['key'])) {
          this.formFormatData['key'].map((item) => {
            this.$refs[`${item}`] && this.$refs[`${item}`].resetFields()
          })
        } else {
          this.$refs[this.formFormatData['key']].resetFields()
        }
      }
    },
    clearValidate(current) {
      if (current) {
        this.$refs[current].clearValidate()
      } else {
        if (Array.isArray(this.formFormatData['key'])) {
          this.formFormatData['key'].map((item) => {
            this.$refs[`${item}`] && this.$refs[`${item}`].clearValidate()
          })
        } else {
          this.$refs[this.formFormatData['key']].clearValidate()
        }
      }
    },
    resetFormFormat(current = false) {
      const { apiConfig } = this['formFormatData']['api']
      const [copyFormData = {}] = require('@/filters/index').assignCopy(current || this.formCopyEmpty)
      this.formFormatData.formData = copyFormData
      if (apiConfig && apiConfig['editForm'] && apiConfig['editForm']['filters']) {
        const keys = Object.keys(apiConfig['editForm']['filters'])
        if (keys.length > 0) {
          keys.map((item) => {
            apiConfig['editForm']['filters'][item]['initData'] = []
          })
        }
      }
    },
    validateCheckArray(rule, value, callback) {
      this.loading = false
      const { message } = rule
      if (!Array.isArray(value) || (Array.isArray(value) && value.length === 0)) {
        this.loading = false
        return callback(new Error(`${message}！~`))
      } else {
        this.loading = false
        callback()
      }
    },
    validateForm({ router = {} }) {
      // if (this.hasValidate) {
      //   this.validateFormList.map((keys) => {
      // this.$refs[keys].validate((valid, object) => {
      //   if (!valid) {
      // this.$message.error('表单数据有误，请确认并修改后重新提交')
      // return false
      //   }
      // })
      //   })
      // }
      let isError = false
      if (!Array.isArray(this.formFormatData['key'])) {
        this.formFormatData['key'] = [this.formFormatData['key']]
      }

      this.formFormatData['key'].map((item) => {
        if (this.$refs[item]) {
          this.$refs[item].validate((valid, object) => {
            if (!valid) {
              isError = true

              this.$message.error('表单数据有误，请确认并修改后重新提交')
              return false
            }
          })
        }
      })
      !isError && this.requestFormatSubmit(router)
    },
    // 表单保存
    formFormatSubmit(params = {}) {
      console.log("sssssffff")
      if (params) {
        this.validateForm(params)
      } else {
        this.loading = true
      }
    },
    resetDialogFormData(resetData) {
      if (resetData) {
        this.formFormatData.formData = resetData
      } else {
        this.resetField()
      }
      const editForm = this.formFormatData.api['editForm']
      if (editForm) {
        const { filters = {} } = editForm
        const hasFilters = Object.keys(filters)
        if (hasFilters.length > 0) {
          hasFilters.map((item, index) => {
            if (item === 'img' || item === 'address' || item === 'map') {
              const { bindInit } = filters[item]
              this.formFormatCallFiltersEach(bindInit, {}, (bindItem, initData) => {
                this[bindItem].initList = []
              }, true)
            }
          })
        }

        const { redirect = 'id' } = editForm
        this.formFormatData.api['editForm']['params'][`${redirect}`] = ''
      }
    },
    requestFormatSubmit({ type = '', path = '', code = '', query = {} }) {
      this.isSaveLoding = true
      this.loading = true
      const isEdit = this.formFormatData.api['editForm'] && this.formFormatData.api['editForm']['api'] && ((this.$route.query && this.hasFormEditRouteId) || (this.formFormatData.api['editForm']['params'] && this.formFormatData.api['editForm']['params']['always']))
      this['formFormatData']['api']['submitForm'](this.getFormFormatData()).then(response => {
        const { data: formData = {} } = response
        console.log(formData, '=================data')
        this.loading = false
        console.log('loading', this.loading)

        const { bindDialog, closeDialog = true, hasMessage = true } = this['formFormatData']['model'] || {}
        if (formData.code === 0 && hasMessage) {
          this.$message.error(formData.message || isEdit && this.hasFormEditRouteId ? '编辑失败' : '保存失败')
        } else {
          if (this.changeMsg === 'pushMessage') {
            this.$message.success('消息已加入队列，请等待!')
          } else {
            this.isSaveLoding = true
            console.log('dddd', hasMessage, isEdit, this.hasFormEditRouteId)
            hasMessage && (this.$message.success(isEdit && this.hasFormEditRouteId ? '编辑成功' : '保存成功'))
          }
          if (code === 1 && type && path) {
            path == '/application/leaderManagementAdd' ? this.$router[type]({ path, query: { reg_id: formData.data } }) : this.$router[type]({ path, query })
          }
        }

        this.isSaveLoding = false
        if (!!bindDialog && typeof bindDialog === 'string' && closeDialog) {
          this[`${bindDialog}`] = false
          this.getTableList && this.getTableList()
        }
        this.formFormatCallBack && this.formFormatCallBack(this['formFormatData']['formData'], 'submitForm', response)
      }).catch(() => {
        this.isSaveLoding = false
        this.loading = false
      })
    },
    // 这里是用来获取表单内容
    getFormFormatData() {
      return this.formFormatData['formData']
    }
  }
}
